import React, { Component } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import Pie from '@/components/Charts/Pie';
import { Card, Input, Col, Row } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import MiniArea from '@/components/Charts/MiniArea';

const visitData = [];
const beginDay = new Date().getTime();
for (let i = 0; i < 20; i += 1) {
  visitData.push({
    x: moment(new Date(beginDay + 1000 * 60 * 60 * i)).format('hh:mm'),
    y: Math.floor(Math.random() * 1000) + 500,
  });
}

// 学生所属专业
const specialities = {
  ch: '测绘专业',
  yg: '遥感专业',
  zh: '自环专业',
  cx: '城乡专业',
  dx: '地信专业',
  tg: '土管专业',
};

// 所属系
const departments = {
  ch: '测绘中心实验室',
  yg: '遥感科学与技术系',
  zh: '资源环境与城乡规划管理系',
  cx: '土地资源管理系',
  dx: '测量工程系',
  tg: '地理信息科学系',
};

@connect(({ attendance, loading }) => ({
  attendance,
  loading: loading.models.attendance,
}))
class StudentAttendance extends Component {
  state = {
    selectedRows: [],
    tabActiveKey: 'all',
  };

  columns = [
    {
      title: () => {
        const { tabActiveKey } = this.state;
        switch (tabActiveKey) {
          case 'all':
            return '学号/教职工号';
          case 'teacher':
            return '教职工号';
          case 'student':
            return '学号';
          default:
            break;
        }
        return '学号/教职工号';
      },
      dataIndex: 'key',
      key: 'key',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '角色',
      dataIndex: 'role',
      key: 'role',
      render: text => (text === 'teacher' ? '教职工' : '学生'),
    },
    {
      title: '所属系/专业',
      dataIndex: 'division',
      key: 'division',
      render: (text, record) => {
        if (record.role === 'teacher') {
          return departments[text];
        }
        return specialities[text];
      },
    },
    {
      title: '日期',
      dataIndex: 'date',
      key: 'date',
    },
    {
      title: '应签到',
      dataIndex: 'start',
      key: 'start',
    },
    {
      title: '实签到',
      dataIndex: 'checkin',
      key: 'checkin',
      sorter: true,
    },
    {
      title: '应签退',
      dataIndex: 'end',
      key: 'end',
    },
    {
      title: '实签退',
      dataIndex: 'signback',
      key: 'signback',
      sorter: true,
    },
    {
      title: '备注',
      dataIndex: 'desc',
      key: 'desc',
    },
  ];

  tabList = [
    {
      key: 'all',
      tab: '全部',
    },
    {
      key: 'teacher',
      tab: '教职工',
    },
    {
      key: 'student',
      tab: '学生',
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'attendance/fetch',
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'attendance/clear',
    });
  }

  handleFormSubmit = val => {
    const { dispatch } = this.props;
    const { tabActiveKey } = this.state;

    dispatch({
      type: 'attendance/fetch',
      payload: {
        name: val,
        role: tabActiveKey,
      },
    });
  };

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const getValue = obj =>
      Object.keys(obj)
        .map(key => obj[key])
        .join(',');

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'attendance/fetch',
      payload: params,
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleTabChange = role => {
    const { dispatch } = this.props;

    dispatch({
      type: 'attendance/fetch',
      payload: {
        role: role !== 'all' ? role : '',
      },
      callback: () => {
        this.setState({
          tabActiveKey: role,
        });
      },
    });
  };

  render() {
    const {
      loading,
      attendance: { attendanceHistory },
    } = this.props;
    const { selectedRows, tabActiveKey } = this.state;

    const mainSearch = (
      <div style={{ textAlign: 'center' }}>
        <Input.Search
          placeholder="请输入"
          enterButton="搜索"
          size="large"
          onSearch={this.handleFormSubmit}
          style={{ width: 522 }}
        />
      </div>
    );

    return (
      <PageHeaderWrapper
        title="考勤明细"
        content={mainSearch}
        tabList={this.tabList}
        tabActiveKey={tabActiveKey}
        onTabChange={this.handleTabChange}
      >
        <Card bordered={false} style={{ marginBottom: 24 }} loading={loading}>
          <StandardTable
            selectedRows={selectedRows}
            data={attendanceHistory}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>

        <Row gutter={16}>
          <Col xl={12} lg={24} sm={24} xs={24} style={{ marginBottom: 24 }}>
            <Card title="通勤率" bordered={false} loading={loading}>
              <Row style={{ padding: '16px 0' }}>
                <Col span={8}>
                  <Pie
                    animate={false}
                    percent={98}
                    subTitle="学院"
                    total="98%"
                    height={128}
                    lineWidth={2}
                  />
                </Col>
                <Col span={8}>
                  <Pie
                    animate={false}
                    color="#5DDECF"
                    percent={99}
                    subTitle="教师"
                    total="99%"
                    height={128}
                    lineWidth={2}
                  />
                </Col>
                <Col span={8}>
                  <Pie
                    animate={false}
                    color="#2FC25B"
                    percent={93}
                    subTitle="学生"
                    total="93%"
                    height={128}
                    lineWidth={2}
                  />
                </Col>
              </Row>
            </Card>
          </Col>
          <Col xs={24} sm={24} md={24} lg={12} style={{ marginBottom: 24 }}>
            <Card bordered={false} title="打卡时段统计" loading={loading}>
              <MiniArea line color="#cceafe" data={visitData} height={160} />
            </Card>
          </Col>
        </Row>
      </PageHeaderWrapper>
    );
  }
}

export default StudentAttendance;
